package com.raisecom.util;

import java.awt.Toolkit;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class LimitedLengthDocument extends PlainDocument {
	private static final long serialVersionUID = -1691894166592533136L;

  	private int len;
	private JTextField textField;
	
	public LimitedLengthDocument(JTextField textField, int len){
		this.textField = textField;
		this.len=len;
	}
	public void insertString(int offs, String str, AttributeSet as)throws BadLocationException {
		if(str==null){
			return ;
		}else if("".equals(str)){
			Toolkit.getDefaultToolkit().beep();
			return;
		}else if(textField.getText().length()+str.length()<=len){
			super.insertString(offs, str.toUpperCase(), as);
		}else if(textField.getText().length()+str.length()>len){
			super.insertString(offs, str.substring(0,len-textField.getText().length()), as);
		}
	}

}
